iT邦幫忙

2022 iThome 鐵人賽

DAY 15
0
Software Development

30而Leet{code}系列 第 15

D15 - [Linked List] Remove Nth Node From End of List

  • 分享至 

  • xImage
  •  

這一題困難的點在於,因為題目給的 Linked List 沒有紀錄現在的長度,所以你很難直接算出到底哪個點是倒數第N個點.

問題

https://leetcode.com/problems/remove-nth-node-from-end-of-list/

Given the head of a linked list, remove the nth node from the end of the list and return its head.

Example 1:
Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]

Example 2:
Input: head = [1], n = 1
Output: []

Example 3:
Input: head = [1,2], n = 1
Output: [1]

我的答案

Two Pointers 方法

slow 指標比 fast 指標慢 n+1 個節點.
則當 fast 指標到達最後一個節點時, slow 指標剛好落在倒數第n個節點的前一個節點.
這時我們只要處理 slow 指標,把 slow 指標的下一個節點指向下下個節點即是答案.

Python

class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        fast = head
        slow = ListNode(-1,  head)

        for _ in range(n):
            fast = fast.next

        while fast != None:
            fast = fast.next
            slow = slow.next

        if slow.next == head:
            return head.next

        slow.next= slow.next.next
        return head

Go

func removeNthFromEnd(head *ListNode, n int) *ListNode {

    fast := head
    slow := &ListNode{0, head}

    // move fast only
    for i := 0; i < n ; i++ {
        fast = fast.Next
    }

    // move together
    for fast != nil {
        fast = fast.Next
        slow = slow.Next
    }

    //remove the nth
    if slow.Next == head {
        return head.Next
    }
    slow.Next= slow.Next.Next
    return head

}


上一篇
D14 - [Linked List] 用 Go 實作 Linked List
下一篇
D16 - [Linked List] Delete the Middle Node of a Linked List
系列文
30而Leet{code}30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言